window.grammar = {}

( ->

##private

  $grammar = []

  $gleft_table_click = ->
    $('#gleft table tr').removeClass 'active'
    $(this).addClass 'active'
    short_desc = $(this).find('td')[0].innerHTML
    grammar = $grammar.filter (g) -> g.d == short_desc
    grammar = grammar[0]
    $('#gstruct').html grammar.d
    $('#gusage').html grammar.ld
    $('#gexpl').html grammar.tr

##public

  grammar.load = ->
    $.getJSON '/grammars', { l: login.language, c: login.class }, (data) ->
      $.each data, (i, g) ->
        $grammar.push g
        console.log(g)
        element = $("<tr><td>#{g.d}</td></tr>")
        element.click $gleft_table_click
        $('#gchooser').append element
        $.each g.eg, (i, e) ->
          $('#gchooser').append "<tr><td>#{e.co}</td><td>#{e.tr}</td></tr>"
      $('#gchooser').children().first().addClass('active')

##initialize

  grammar.initialize = ->
    $('#addegbtn').click ->
      if $('#addegbtn').text().indexOf("Save") != -1
        #TODO: Test for ClearField classes instead
        if $('#gegtext').val() == "" or $('#gtrtext').val() == "" or
            $('#gegtext').val() == "Example" or $('#gtrtext') == "Translation"
          $('#ent').notify('create', { text: "Please enter both an example and a translation!" })
      else
        $('#gaddrow').fadeIn()
        $('#addegbtn').text ":) Save"
        $('#cancelegbtn').fadeIn()
    $('#cancelegbtn').click ->
      $('#gaddrow').fadeOut()
      $('#cancelegbtn').fadeOut()
      $('#addegbtn').text "+ Add Example"

)()
